package com.mergeades.chp04;

import java.sql.Connection;
import java.util.LinkedList;

public class ConnectPool {

    private final LinkedList<Connection> pool = new LinkedList<>();

    public ConnectPool(int initialSize) {
        for (int i = 0; i < initialSize; i++) {
            pool.addLast(ConnectionDriver.createConnection());
        }
    }

    /**
     * 释放连接到连接池，释放后，会通知其他等待线程
     *
     * @param conn connection
     */
    public void releaseConnection(Connection conn) {
        if (conn != null) {
            synchronized (pool) {
                pool.addLast(conn);
                pool.notifyAll();//归还连接后，通知所有等待线程
            }
        }
    }

    /**
     * 获取连接，如果在 mills 超时，则返回null
     *
     * @param mills 超时时间
     * @return 连接池，可能返回为null
     */
    public Connection fetchConnection(long mills) throws InterruptedException {
        synchronized (pool) {
            if (mills < 0) {
                while (pool.isEmpty()) {
                    pool.wait();
                }
                return pool.removeFirst();
            } else {
                long future = System.currentTimeMillis() + mills;
                long remaining = mills;
                while (pool.isEmpty() && remaining > 0) {
                    pool.wait(remaining);
                    remaining = future - System.currentTimeMillis();
                }
                Connection result = null;
                if (!pool.isEmpty()) {
                    result = pool.removeFirst();
                }
                return result;
            }
        }
    }
}
